import { CANVAS_WIDTH, CANVAS_HEIGHT } from '../utils/constants.js'

// Boss基类
export default class Boss {
  constructor(width, height, speed, health, score, type, imageSrc) {
    this.width = width
    this.height = height
    this.speed = speed
    this.health = health
    this.maxHealth = health
    this.score = score
    this.type = type

    // Boss位置 - 初始位置在屏幕上方中央
    this.x = (CANVAS_WIDTH - width) / 2
    this.y = -height

    // Boss状态
    this.active = true
    this.isEntering = true // 是否正在入场
    this.currentPhase = 1 // 当前阶段
    this.phaseThresholds = [0.7, 0.4, 0.1] // 阶段切换的生命值百分比阈值

    // 移动相关属性
    this.movementPattern = 'horizontal' // 默认为水平移动
    this.movementDirection = 1 // 1表示向右，-1表示向左
    this.movementTimer = 0
    this.movementInterval = 3000 // 改变移动方向的间隔（毫秒）
    this.entrySpeed = speed * 0.5 // 入场速度

    // 视觉效果相关属性
    this.flashTimer = 0
    this.isFlashing = false

    // 加载图像
    this.image = new Image()
    this.image.src = imageSrc
  }

  update(timestamp) {
    // 处理入场动画
    if (this.isEntering) {
      this.y += this.entrySpeed
      if (this.y >= this.height * 0.5) {
        this.isEntering = false
      }
      return
    }

    // 根据当前移动模式更新位置
    this.updateMovement(timestamp)

    // 更新视觉效果
    this.updateVisualEffects(timestamp)

    // 检查是否需要切换阶段
    this.checkPhaseTransition()
  }

  updateMovement(timestamp) {
    // 更新移动计时器
    this.movementTimer += timestamp - (this.lastTimestamp || timestamp)
    this.lastTimestamp = timestamp

    // 根据移动模式更新位置
    switch (this.movementPattern) {
      case 'horizontal':
        this.updateHorizontalMovement()
        break
      case 'arc':
        this.updateArcMovement(timestamp)
        break
      case 'zigzag':
        this.updateZigzagMovement(timestamp)
        break
      default:
        this.updateHorizontalMovement()
    }

    // 定期改变移动方向
    if (this.movementTimer >= this.movementInterval) {
      this.movementTimer = 0
      this.changeMovementDirection()
    }
  }

  updateHorizontalMovement() {
    // 水平移动
    this.x += this.speed * this.movementDirection

    // 边界检测
    if (this.x <= 0) {
      this.x = 0
      this.movementDirection = 1
    } else if (this.x + this.width >= CANVAS_WIDTH) {
      this.x = CANVAS_WIDTH - this.width
      this.movementDirection = -1
    }
  }

  updateArcMovement(timestamp) {
    // 弧形移动 - 使用正弦函数
    const centerX = CANVAS_WIDTH / 2 - this.width / 2
    const amplitude = CANVAS_WIDTH * 0.4 // 振幅
    const period = 5000 // 周期（毫秒）

    this.x =
      centerX +
      Math.sin(((timestamp % period) / period) * Math.PI * 2) * amplitude
  }

  updateZigzagMovement(timestamp) {
    // 之字形移动
    this.updateHorizontalMovement()

    // 垂直方向上的小幅度移动
    const verticalAmplitude = 20
    const verticalPeriod = 2000 // 毫秒

    const verticalOffset =
      Math.sin(((timestamp % verticalPeriod) / verticalPeriod) * Math.PI * 2) *
      verticalAmplitude
    this.y = this.height * 0.5 + verticalOffset
  }

  changeMovementDirection() {
    // 改变移动方向
    this.movementDirection *= -1
  }

  updateVisualEffects(timestamp) {
    // 受伤闪烁效果
    if (this.isFlashing) {
      this.flashTimer += timestamp - (this.lastFlashTimestamp || timestamp)
      this.lastFlashTimestamp = timestamp

      if (this.flashTimer >= 300) {
        // 闪烁持续300毫秒
        this.isFlashing = false
        this.flashTimer = 0
      }
    }
  }

  checkPhaseTransition() {
    // 检查是否需要切换阶段
    const healthPercent = this.health / this.maxHealth
    const nextPhase = this.currentPhase + 1

    if (nextPhase <= this.phaseThresholds.length + 1) {
      const threshold = this.phaseThresholds[nextPhase - 2]
      if (healthPercent <= threshold) {
        this.currentPhase = nextPhase
        this.onPhaseTransition(nextPhase)
      }
    }
  }

  onPhaseTransition(newPhase) {
    // 阶段切换时的行为，子类可以重写此方法
    // 默认行为：改变移动模式
    switch (newPhase) {
      case 2:
        this.movementPattern = 'arc'
        break
      case 3:
        this.movementPattern = 'zigzag'
        break
      case 4:
        // 最终阶段，加快速度
        this.speed *= 1.5
        break
    }
  }

  render(ctx) {
    // 如果正在闪烁，则交替显示
    if (this.isFlashing && Math.floor(this.flashTimer / 50) % 2 === 0) {
      ctx.globalAlpha = 0.5
    }

    // 绘制Boss
    ctx.drawImage(this.image, this.x, this.y, this.width, this.height)

    // 重置透明度
    ctx.globalAlpha = 1.0

    // 绘制生命值条
    this.renderHealthBar(ctx)
  }

  renderHealthBar(ctx) {
    const healthBarWidth = CANVAS_WIDTH * 0.8
    const healthBarHeight = 10
    const healthBarX = (CANVAS_WIDTH - healthBarWidth) / 2
    const healthBarY = 20

    // 背景
    ctx.fillStyle = '#333'
    ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight)

    // 生命值
    const healthPercent = this.health / this.maxHealth

    // 根据生命值百分比改变颜色
    let healthColor
    if (healthPercent > 0.6) {
      healthColor = '#00ff00' // 绿色
    } else if (healthPercent > 0.3) {
      healthColor = '#ffff00' // 黄色
    } else {
      healthColor = '#ff0000' // 红色
    }

    ctx.fillStyle = healthColor
    ctx.fillRect(
      healthBarX,
      healthBarY,
      healthBarWidth * healthPercent,
      healthBarHeight
    )

    // 绘制阶段标记
    this.renderPhaseMarkers(
      ctx,
      healthBarX,
      healthBarY,
      healthBarWidth,
      healthBarHeight
    )

    // 绘制Boss名称和生命值文本
    ctx.fillStyle = '#ffffff'
    ctx.font = '16px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(
      `${this.name || 'BOSS'} - ${Math.floor(healthPercent * 100)}%`,
      CANVAS_WIDTH / 2,
      healthBarY + healthBarHeight + 16
    )
  }

  renderPhaseMarkers(ctx, barX, barY, barWidth, barHeight) {
    // 绘制阶段标记
    ctx.strokeStyle = '#ffffff'
    ctx.lineWidth = 2

    for (const threshold of this.phaseThresholds) {
      const markerX = barX + barWidth * threshold

      ctx.beginPath()
      ctx.moveTo(markerX, barY - 5)
      ctx.lineTo(markerX, barY + barHeight + 5)
      ctx.stroke()
    }
  }

  takeDamage(amount) {
    // 受到伤害
    this.health -= amount

    // 触发闪烁效果
    this.isFlashing = true
    this.flashTimer = 0

    // 检查是否被击败
    if (this.health <= 0) {
      this.active = false
      return true // 返回true表示Boss被击败
    }

    return false
  }

  isOutOfScreen() {
    return this.y > CANVAS_HEIGHT
  }
}
